package com.mentaleye.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mentaleye.bean.UserLoginBean;
import com.mentaleye.biz.UserLoginBiz;
import com.mentaleye.dal.model.UserLogin;
import com.mentaleye.service.UserLoginService;
import com.mentaleye.shiro.Constants;
import com.mentaleye.shiro.RedisCache;
import com.mentaleye.shiro.RedisKeyEnum;
import com.mentaleye.util.CommonResult;
import com.mentaleye.util.ObjectUtil;

@Service
public class UserLoginBizImpl implements UserLoginBiz {

	private static Logger logger = Logger.getLogger(UserLoginBiz.class);

	@Autowired
	private UserLoginService dataService;
	
	@Autowired private RedisCache<String, Object> redisCache;

	@Override
	public CommonResult insertRecord(UserLoginBean dataBean) {
		CommonResult result = new CommonResult();
		try {
			UserLogin data = (UserLogin) ObjectUtil.transfer(dataBean, UserLogin.class);
			if (this.dataService.insertRecord(data)) {
				result.setIsSuccess(true);
				result.setResultMsg("插入成功!");
			} else {
				result.setResultMsg("插入失败!");
			}
		} catch (Exception e) {
			logger.debug("账户信息插入异常!", e);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CommonResult insertByList(List<UserLoginBean> beanList) {
		CommonResult result = new CommonResult();
		try {
			List<UserLogin> dataList = ObjectUtil.transferList(beanList, UserLogin.class);
			if (this.dataService.insertByList(dataList)) {
				result.setIsSuccess(true);
				result.setResultMsg("插入成功!");
			} else {
				result.setResultMsg("插入失败!");
			}
		} catch (Exception e) {
			logger.debug("账户信息插入异常!", e);
		}
		return result;
	}

	@Override
	public CommonResult updateRecord(UserLoginBean dataBean) {
		CommonResult result = new CommonResult();
		try {
			UserLogin data = (UserLogin) ObjectUtil.transfer(dataBean, UserLogin.class);
			if (this.dataService.updateRecord(data)) {
				result.setIsSuccess(true);
				result.setResultMsg("更新成功!");
			} else {
				result.setResultMsg("更新失败!");
			}
		} catch (Exception e) {
			logger.debug("账户信息更新异常!", e);
		}
		return result;
	}
	
	@Override
	public CommonResult updateRecordSelective(UserLoginBean dataBean) {
		CommonResult result = new CommonResult();
		try {
			UserLogin data = (UserLogin) ObjectUtil.transfer(dataBean, UserLogin.class);
			if (this.dataService.updateRecordBySelective(data)) {
				result.setIsSuccess(true);
				result.setResultMsg("更新成功!");
			} else {
				result.setResultMsg("更新失败!");
			}
		} catch (Exception e) {
			logger.debug("账户信息更新异常!", e);
		}
		return result;
	}

	@Override
	public UserLogin getBySelective(UserLoginBean dataBean) {
		UserLogin userLogin = null;
		try {
			userLogin = this.dataService.getBySelective(dataBean.getLoginName(), dataBean.getPassword(),
					dataBean.getUserType());
		} catch (Exception e) {
			logger.debug("账户信息查询异常!", e);
		}
		return userLogin;
	}
	
	@Override
	public UserLoginBean getBeanBySelective(UserLoginBean dataBean) {
		UserLogin userLogin=null;
		UserLoginBean userLoginBean = null;
		try {
			userLogin = this.dataService.getBySelective(dataBean.getLoginName(), dataBean.getPassword(),
					dataBean.getUserType());
			userLoginBean=(UserLoginBean) ObjectUtil.transfer(userLogin, UserLoginBean.class);
		} catch (Exception e) {
			logger.debug("账户信息查询异常!", e);
		}
		return userLoginBean;
	}

	@Override
	public CommonResult checkBySelective(UserLoginBean dataBean) {
		CommonResult result = new CommonResult();
		UserLogin userLogin = null;
		try {
			userLogin = this.dataService.getBySelective(dataBean.getLoginName(), dataBean.getPassword(),
					dataBean.getUserType());
			if (userLogin != null) {
				result.setIsSuccess(true);
			} else {
				result.setResultMsg("账户不存在");
			}
		} catch (Exception e) {
			logger.debug("账户信息查询异常!", e);
		}
		return result;
	}

	@Override
	public CommonResult checkLoginName(UserLoginBean dataBean) {
		CommonResult result = new CommonResult();
		List<UserLogin> loginList = null;
		boolean isDuplicate=false;
		try {
			loginList = this.dataService.getListByLoginName(dataBean.getLoginName());
			for (UserLogin userLogin : loginList) {
				if (!userLogin.getLoginId().equals(dataBean.getLoginId())) {
					isDuplicate=true;
					break;
				} 
			}
			if(isDuplicate){
				result.setResultMsg("该账户名称已经存在");
			}
			else
			{
				result.setIsSuccess(true);
			}
		} catch (Exception e) {
			logger.debug("账户信息查询异常!", e);
			result.setResultMsg("账户信息查询异常");
		}
		return result;
	}

	@Override
	public CommonResult checkLogin(UserLoginBean dataBean) {
		CommonResult commonResult = new CommonResult();
		UserLoginBean loginBean = null;
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			commonResult.setIsSuccess(true);
		} else {
			try {
				String loginName = dataBean.getLoginName();
				String password = dataBean.getPassword();
				Integer userType = dataBean.getUserType();
				loginBean=(UserLoginBean) ObjectUtil.transfer(this.dataService.getBySelective(loginName, password, userType), UserLoginBean.class);
				if (loginBean != null) {
					this.redisCache.put(Constants.getRedisKey(RedisKeyEnum.USER_LOGIN, loginName), loginBean);
					AuthenticationToken token = new UsernamePasswordToken(loginName, password);
					subject.login(token);
					commonResult.setIsSuccess(true);
				}
			} catch (Exception e) {
				logger.debug("账户信息查询异常", e);
			}
		}
		return commonResult;
	}

	@Override
	public CommonResult deleteByKeyList(List<Integer> keyList) {
		CommonResult result = new CommonResult();
		try {
			if (this.dataService.deleteByKeyList(keyList)) {
				result.setIsSuccess(true);
				result.setResultMsg("删除成功!");
			} else {
				result.setResultMsg("删除失败!");
			}
		} catch (Exception e) {
			logger.debug("账户信息删除异常!", e);
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getLoginByMap(Map<String, Object> map) {
		List<Map<String, Object>> mapList = null;
		try {
			mapList = this.dataService.getLoginByMap(map);
		} catch (Exception e) {
			logger.debug("账户信息查询异常!", e);
		}
		return mapList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CommonResult toIndex() {
		String loginName = null;
		List<Map<String, Object>> loginList =null;
		CommonResult result=new CommonResult();
		Map<String, Object> map = new HashMap<String, Object>();
		Subject subject = SecurityUtils.getSubject();
		Session session=null;
		if (subject.isAuthenticated()) {
			session = subject.getSession();
			if(session!=null){
				loginList =(List<Map<String, Object>>)session.getAttribute("loginList");
			}
			
			if(loginList==null){
				loginName = (String) subject.getPrincipal();
				map.put("loginName", loginName);
				loginList = this.dataService.getLoginByMap(map);
				session.setAttribute("loginList", loginList);
			}
			
			result.setIsSuccess(true);
			result.setData(loginList);
		}
		else
		{
			subject.logout();
		}
		return result;
	}
	
	@Override
	public void loginOut() {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			if (subject.isAuthenticated()) {
				subject.logout();
			}
		}
	}
}
